<!DOCTYPE html><html lang="zh-CN" data-theme="dark"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>Golang 操作MongoDB | J.のblog</title><meta name="keywords" content="云原生,golang"><meta name="author" content="J."><meta name="copyright" content="J."><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#0d0d0d"><meta name="description" content="MongoDBMongoDB属于非关系型数据库，是由C++编写的分布式文档数据库。内部使用类似于Json的bson二进制格式。 中文手册 https:&#x2F;&#x2F;www.w3cschool.cn&#x2F;mongodb&#x2F; 安装https:&#x2F;&#x2F;www.mongodb.com&#x2F;try&#x2F;download&#x2F;community 自行下载对应操作系统的MongoDB，并运行它。 windows可以下载官方zip，解压即可使用">
<meta property="og:type" content="article">
<meta property="og:title" content="Golang 操作MongoDB">
<meta property="og:url" content="http://dycloudnavite.love/2023/05/09/Go%E6%93%8D%E4%BD%9CMongoDB/index.html">
<meta property="og:site_name" content="J.のblog">
<meta property="og:description" content="MongoDBMongoDB属于非关系型数据库，是由C++编写的分布式文档数据库。内部使用类似于Json的bson二进制格式。 中文手册 https:&#x2F;&#x2F;www.w3cschool.cn&#x2F;mongodb&#x2F; 安装https:&#x2F;&#x2F;www.mongodb.com&#x2F;try&#x2F;download&#x2F;community 自行下载对应操作系统的MongoDB，并运行它。 windows可以下载官方zip，解压即可使用">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://dycloudnavite.love/img/golang.png">
<meta property="article:published_time" content="2023-05-09T06:32:00.000Z">
<meta property="article:modified_time" content="2023-08-30T03:02:58.035Z">
<meta property="article:author" content="J.">
<meta property="article:tag" content="云原生">
<meta property="article:tag" content="golang">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://dycloudnavite.love/img/golang.png"><link rel="shortcut icon" href="/dujie5416/img/touxiang.png"><link rel="canonical" href="http://dycloudnavite.love/2023/05/09/Go%E6%93%8D%E4%BD%9CMongoDB/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/dujie5416/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/dujie5416/',
  algolia: {"appId":"9GWB2VV7GN","apiKey":"dac56ec5b0b1f45281251ee59db4d637","indexName":"blog","hits":{"per_page":6},"languages":{"input_placeholder":"搜索文章","hits_empty":"找不到您查询的内容：${query}","hits_stats":"找到 ${hits} 条结果，用时 ${time} 毫秒"}},
  localSearch: undefined,
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Golang 操作MongoDB',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-08-30 11:02:58'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/xxx.css"><link rel="stylesheet" href="/css/universe.css"><link rel="stylesheet" href="/css/custom.css"><style type="text/css">#toggle-sidebar {bottom: 80px}</style><link rel="stylesheet" href="https://fastly.jsdelivr.net/gh/tzy13755126023/BLOG_SOURCE/css/function.min.css"><link rel="stylesheet" href="/css/rightMenu.css"><style type="text/css">#toggle-sidebar {left:100px}</style><!-- hexo injector head_end start --><link rel="stylesheet" href="https://cdn.cbd.int/hexo-butterfly-clock-anzhiyu/lib/clock.min.css" /><!-- hexo injector head_end end --><meta name="generator" content="Hexo 6.2.0"><link rel="alternate" href="/dujie5416/atom.xml" title="J.のblog" type="application/atom+xml">
</head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/dujie5416/img/touxiang.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/dujie5416/archives/"><div class="headline">文章</div><div class="length-num">73</div></a><a href="/dujie5416/tags/"><div class="headline">标签</div><div class="length-num">17</div></a><a href="/dujie5416/categories/"><div class="headline">分类</div><div class="length-num">11</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/dujie5416/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/dujie5416/img/longzhu.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/dujie5416/">J.のblog</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/dujie5416/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Golang 操作MongoDB</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-05-09T06:32:00.000Z" title="发表于 2023-05-09 14:32:00">2023-05-09</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-08-30T03:02:58.035Z" title="更新于 2023-08-30 11:02:58">2023-08-30</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/dujie5416/categories/golang/">golang</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Golang 操作MongoDB"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="MongoDB"><a href="#MongoDB" class="headerlink" title="MongoDB"></a>MongoDB</h1><p>MongoDB属于非关系型数据库，是由C++编写的分布式文档数据库。内部使用类似于Json的bson二进制格式。</p>
<p>中文手册</p>
<p><a target="_blank" rel="noopener" href="https://www.w3cschool.cn/mongodb/">https://www.w3cschool.cn/mongodb/</a></p>
<h4 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h4><p><a target="_blank" rel="noopener" href="https://www.mongodb.com/try/download/community">https://www.mongodb.com/try/download/community</a></p>
<p>自行下载对应操作系统的MongoDB，并运行它。</p>
<p>windows可以下载官方zip，解压即可使用。</p>
<table>
<thead>
<tr>
<th>组件</th>
<th>文件名</th>
</tr>
</thead>
<tbody><tr>
<td>Server</td>
<td>mongod.exe</td>
</tr>
<tr>
<td>Router</td>
<td>mongos.exe，Query Router,Sharding Cluster</td>
</tr>
<tr>
<td>Client</td>
<td>mongo.exe</td>
</tr>
<tr>
<td>MonitoringTools</td>
<td>mongostat.exe，mongotop.exe</td>
</tr>
<tr>
<td>ImportExportTools</td>
<td>mongostat.exe，mongotop.exe</td>
</tr>
<tr>
<td>MiscellaneousTools</td>
<td>bsondump.exe，mongofiles.exe，mongooplog.exe，mongoperf.exe</td>
</tr>
</tbody></table>
<h3 id="运行"><a href="#运行" class="headerlink" title="运行"></a>运行</h3><pre class="line-numbers language-go" data-language="go"><code class="language-go">$ cd <span class="token operator">/</span>o<span class="token operator">/</span>mongodb3<span class="token punctuation">.</span><span class="token number">6</span><span class="token operator">/</span>bin
$ <span class="token punctuation">.</span><span class="token operator">/</span>mongod<span class="token punctuation">.</span>exe
<span class="token number">2019</span><span class="token operator">-</span><span class="token number">08</span><span class="token operator">-</span>02T03<span class="token punctuation">:</span><span class="token number">26</span><span class="token punctuation">:</span><span class="token number">13.234</span><span class="token operator">-</span><span class="token number">0700</span> I STORAGE <span class="token punctuation">[</span>initandlisten<span class="token punctuation">]</span> exception ininitAndListen<span class="token punctuation">:</span> NonExistentPath<span class="token punctuation">:</span> Data directory O<span class="token punctuation">:</span>\data\db\ not found<span class="token punctuation">.</span><span class="token punctuation">,</span> terminating
启动服务出错，原因在于找不到数据目录。默认是<span class="token operator">/</span>data<span class="token operator">/</span>db
windows下在当前盘符根目录下创建目录即可<span class="token string">`o:/data/db`</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>选项说明</p>
<ul>
<li>--bind_ip  ip逗号分隔IP地址。默认为localhost</li>
<li>--bind_ip_all  绑定所有本地ip地址</li>
<li>--port port端口，默认27017</li>
<li>--dbpath  数据路径，却省委&#x2F;data&#x2F;db</li>
<li>--logpath 指定日志路径，代替stdout，默认是控制台打印日志</li>
<li>-f file 指定配置文件，yaml格式</li>
<li>注册windows服务<ul>
<li>--install 注册windows服务</li>
<li>--serviceName name服务名称</li>
<li>--serviceDisplayName name 服务显示名</li>
</ul>
</li>
</ul>
<h3 id="配置文件"><a href="#配置文件" class="headerlink" title="配置文件"></a>配置文件</h3><p>mongodb配置使用Yaml格式</p>
<ul>
<li>嵌套使用缩进完成，不支持Tab等制表符，支持空格<ul>
<li>缩进空格数不限制，只要同一级元素对齐就行</li>
</ul>
</li>
<li>冒号后要有空格</li>
<li>大小写敏感</li>
<li>#表示注释</li>
<li>字符串不需要引号，有特殊字符串时可以使用引号</li>
<li>布尔<ul>
<li>true、True、TRUE、yes、YES都是真</li>
<li>false、False、FALSE、no、NO都是假</li>
</ul>
</li>
<li>null、Null、~波浪线都是空，不指定值默认也是空</li>
</ul>
<p>Yaml参考<a target="_blank" rel="noopener" href="https://www.w3cschool.cn/iqmrhf/dotvpozt.html"> https://www.w3cschool.cn/iqmrhf/dotvpozt.html</a></p>
<p>配置 <a target="_blank" rel="noopener" href="http://mongoing.com/docs/reference/configuration-options.html">http://mongoing.com/docs/reference/configuration-options.html</a></p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">systemLog<span class="token punctuation">:</span>
   destination<span class="token punctuation">:</span> file
   path<span class="token punctuation">:</span> 'o<span class="token punctuation">:</span><span class="token operator">/</span>mongodb3<span class="token punctuation">.</span><span class="token number">6</span><span class="token operator">/</span>logs<span class="token operator">/</span>mongod<span class="token punctuation">.</span>log'
   logAppend<span class="token punctuation">:</span>  <span class="token boolean">true</span>
storage<span class="token punctuation">:</span>
   dbPath<span class="token punctuation">:</span> <span class="token string">"o:/mongodb3.6/db"</span>
net<span class="token punctuation">:</span>
   bindIp<span class="token punctuation">:</span> <span class="token string">"127.0.0.1"</span>
   port<span class="token punctuation">:</span> <span class="token number">27017</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>选项</p>
<ul>
<li>systemLog<ul>
<li>destination，缺省是输出日志到std，file表示输出到文件</li>
<li>path，日志文件路径。文件目录必须存在</li>
<li>logAppend，true表示在已存在的日志文件追加。默认为false，每次启动服务创建新的日志</li>
</ul>
</li>
<li>storage<ul>
<li>dbPath，必须指定mongodb的数据目录，目录必须存在</li>
</ul>
</li>
<li>net<ul>
<li>bindIp ，缺省绑定到127.0.0.1</li>
<li>port 端口，缺省27017，客户端连接用的</li>
</ul>
</li>
</ul>
<p>Windows下注册为服务的命令如下，使用了配置文件：</p>
<p><code>$ mongod.exe -f &quot;o:/mongodb3.6/bin/mongod.yml&quot; --serviceName mongod --serviceDisplayName mongo --install</code></p>
<p>注意，注册服务得需要管理员权限。</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">storage<span class="token punctuation">:</span>
   dbPath<span class="token punctuation">:</span> <span class="token string">"o:/mongodb3.6/db"</span>
net<span class="token punctuation">:</span>
   bindIp<span class="token punctuation">:</span> <span class="token string">"127.0.0.1"</span>
   port<span class="token punctuation">:</span> <span class="token number">27017</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>没有配置日志，信息将显示在控制台中</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">$ pwd
<span class="token operator">/</span>o<span class="token operator">/</span>mongodb3<span class="token punctuation">.</span><span class="token number">6</span>
$ mongod<span class="token punctuation">.</span>exe <span class="token operator">-</span>f <span class="token punctuation">.</span><span class="token operator">/</span>mongod<span class="token punctuation">.</span>yml<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<h3 id="客户端"><a href="#客户端" class="headerlink" title="客户端"></a>客户端</h3><h5 id="客户端连接"><a href="#客户端连接" class="headerlink" title="客户端连接"></a>客户端连接</h5><pre class="line-numbers language-go" data-language="go"><code class="language-go">$ bin<span class="token operator">/</span>mongo<span class="token punctuation">.</span>exe
MongoDB shell version v3<span class="token punctuation">.</span><span class="token number">6.13</span>
help 打开帮助
show dbs     查看当前有哪些库
use blog     有就切换过去，没有就创建后切换过去。刚创建的并不在数据库列表中，需要写入数据后才能看到
db           查看当前数据库
db<span class="token punctuation">.</span>users<span class="token punctuation">.</span><span class="token function">insert</span><span class="token punctuation">(</span><span class="token punctuation">&#123;</span>user<span class="token punctuation">:</span><span class="token string">"tom"</span><span class="token punctuation">,</span> age<span class="token punctuation">:</span><span class="token number">20</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span> db指代当前数据库；users集合名<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<p>也可以使用官方的可视化工具Compass。<a target="_blank" rel="noopener" href="https://www.mongodb.com/products/compass">https://www.mongodb.com/products/compass</a></p>
<h5 id="驱动"><a href="#驱动" class="headerlink" title="驱动"></a>驱动</h5><p>驱动链接：<a target="_blank" rel="noopener" href="https://www.mongodb.com/docs/drivers/">https://www.mongodb.com/docs/drivers/</a></p>
<p>Go驱动：<a target="_blank" rel="noopener" href="https://www.mongodb.com/docs/drivers/go/current/"> https://www.mongodb.com/docs/drivers/go/current/</a></p>
<p>驱动安装：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">$ <span class="token keyword">go</span> get <span class="token keyword">go</span><span class="token punctuation">.</span>mongodb<span class="token punctuation">.</span>org<span class="token operator">/</span>mongo<span class="token operator">-</span>driver<span class="token operator">/</span>mongo<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<h5 id="连接字符串"><a href="#连接字符串" class="headerlink" title="连接字符串"></a>连接字符串</h5><p><a target="_blank" rel="noopener" href="https://www.mongodb.com/docs/manual/reference/connection-string/#examples">https://www.mongodb.com/docs/manual/reference/connection-string/#examples</a></p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">mongodb<span class="token punctuation">:</span><span class="token operator">/</span><span class="token operator">/</span><span class="token punctuation">[</span>username<span class="token punctuation">:</span>password@<span class="token punctuation">]</span>host1<span class="token punctuation">[</span><span class="token punctuation">:</span>port1<span class="token punctuation">]</span><span class="token punctuation">[</span><span class="token punctuation">,</span><span class="token operator">...</span>hostN<span class="token punctuation">[</span><span class="token punctuation">:</span>portN<span class="token punctuation">]</span><span class="token punctuation">]</span>
<span class="token punctuation">[</span><span class="token operator">/</span><span class="token punctuation">[</span>defaultauthdb<span class="token punctuation">]</span><span class="token punctuation">[</span>?options<span class="token punctuation">]</span><span class="token punctuation">]</span>
mongodb<span class="token punctuation">:</span><span class="token operator">/</span><span class="token operator">/</span>wayne<span class="token punctuation">:</span>wayne@mongodb0<span class="token punctuation">.</span>example<span class="token punctuation">.</span>com<span class="token punctuation">:</span><span class="token number">27017</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>链接例子<a target="_blank" rel="noopener" href="https://www.mongodb.com/docs/drivers/go/current/fundamentals/connection/#connection-example">https://www.mongodb.com/docs/drivers/go/current/fundamentals/connection/#connection-example</a></p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token punctuation">(</span>
	<span class="token string">"context"</span>
	<span class="token string">"fmt"</span>

	<span class="token string">"go.mongodb.org/mongo-driver/bson"</span>
	<span class="token string">"go.mongodb.org/mongo-driver/mongo"</span>
	<span class="token string">"go.mongodb.org/mongo-driver/mongo/options"</span>
<span class="token punctuation">)</span>

<span class="token comment">// Replace the placeholder with your Atlas connection string</span>
<span class="token keyword">const</span> uri <span class="token operator">=</span> <span class="token string">"&lt;connection string>"</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>

	<span class="token comment">// Use the SetServerAPIOptions() method to set the Stable API version to 1</span>
	serverAPI <span class="token operator">:=</span> options<span class="token punctuation">.</span><span class="token function">ServerAPI</span><span class="token punctuation">(</span>options<span class="token punctuation">.</span>ServerAPIVersion1<span class="token punctuation">)</span>
	opts <span class="token operator">:=</span> options<span class="token punctuation">.</span><span class="token function">Client</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">ApplyURI</span><span class="token punctuation">(</span>uri<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">SetServerAPIOptions</span><span class="token punctuation">(</span>serverAPI<span class="token punctuation">)</span>

	<span class="token comment">// Create a new client and connect to the server</span>
	client<span class="token punctuation">,</span> err <span class="token operator">:=</span> mongo<span class="token punctuation">.</span><span class="token function">Connect</span><span class="token punctuation">(</span>context<span class="token punctuation">.</span><span class="token function">TODO</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> opts<span class="token punctuation">)</span>

	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
		<span class="token function">panic</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
	<span class="token punctuation">&#125;</span>
	<span class="token keyword">defer</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
		<span class="token keyword">if</span> err <span class="token operator">=</span> client<span class="token punctuation">.</span><span class="token function">Disconnect</span><span class="token punctuation">(</span>context<span class="token punctuation">.</span><span class="token function">TODO</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
			<span class="token function">panic</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
		<span class="token punctuation">&#125;</span>
	<span class="token punctuation">&#125;</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

	<span class="token comment">// Send a ping to confirm a successful connection</span>
	<span class="token keyword">var</span> result bson<span class="token punctuation">.</span>M
	<span class="token keyword">if</span> err <span class="token operator">:=</span> client<span class="token punctuation">.</span><span class="token function">Database</span><span class="token punctuation">(</span><span class="token string">"admin"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">RunCommand</span><span class="token punctuation">(</span>context<span class="token punctuation">.</span><span class="token function">TODO</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> bson<span class="token punctuation">.</span>D<span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span><span class="token string">"ping"</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Decode</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>result<span class="token punctuation">)</span><span class="token punctuation">;</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
		<span class="token function">panic</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
	<span class="token punctuation">&#125;</span>
	fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"Pinged your deployment. You successfully connected to MongoDB!"</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>连接副本集</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">mongodb<span class="token punctuation">:</span><span class="token operator">/</span><span class="token operator">/</span>host1<span class="token punctuation">:</span><span class="token number">27017</span><span class="token punctuation">,</span>host2<span class="token punctuation">:</span><span class="token number">27017</span><span class="token punctuation">,</span>host3<span class="token punctuation">:</span><span class="token number">27017</span><span class="token operator">/</span>?replicaSet<span class="token operator">=</span>myRS<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>


<h5 id="账号密码认证连接"><a href="#账号密码认证连接" class="headerlink" title="账号密码认证连接"></a>账号密码认证连接</h5><p>官网：<a target="_blank" rel="noopener" href="https://www.mongodb.com/docs/drivers/go/current/fundamentals/auth/">https://www.mongodb.com/docs/drivers/go/current/fundamentals/auth/</a></p>
<h6 id="支持的机制"><a href="#支持的机制" class="headerlink" title="支持的机制"></a>支持的机制</h6><p>Go驱动程序支持以下身份验证机制</p>
<ul>
<li><a target="_blank" rel="noopener" href="https://www.mongodb.com/docs/drivers/go/current/fundamentals/auth/#std-label-golang_sha_256">SCRAM-SHA-256</a></li>
<li><a target="_blank" rel="noopener" href="https://www.mongodb.com/docs/drivers/go/current/fundamentals/auth/#std-label-golang-sha-1">SCRAM-SHA-1</a></li>
<li><a target="_blank" rel="noopener" href="https://www.mongodb.com/docs/drivers/go/current/fundamentals/auth/#std-label-golang-mongodb-cr">MONGODB-CR</a></li>
<li><a target="_blank" rel="noopener" href="https://www.mongodb.com/docs/drivers/go/current/fundamentals/auth/#std-label-golang-mongodb-aws">MongoDB-AWS</a></li>
<li><a target="_blank" rel="noopener" href="https://www.mongodb.com/docs/drivers/go/current/fundamentals/auth/#std-label-golang-x509">X.509</a></li>
</ul>
<p>Go Driver通过身份验证机制建立连接<a target="_blank" rel="noopener" href="https://pkg.go.dev/go.mongodb.org/mongo-driver@v1.12.1/mongo#Client">客户</a>类型。该Client类型指定用作连接选项的机制和凭据。<a target="_blank" rel="noopener" href="https://pkg.go.dev/go.mongodb.org/mongo-driver@v1.12.1/mongo/options#Credential">凭据</a>类型。要配置这些选项，请将Credential类型传递给<a target="_blank" rel="noopener" href="https://pkg.go.dev/go.mongodb.org/mongo-driver@v1.12.1/mongo/options#ClientOptions.SetAuth">设置验证()</a> 的方法客户<a target="_blank" rel="noopener" href="https://pkg.go.dev/go.mongodb.org/mongo-driver@v1.12.1/mongo/options#ClientOptions">选项类型</a>。</p>
<h6 id="约定示例"><a href="#约定示例" class="headerlink" title="约定示例"></a>约定示例</h6><p>每个身份验证机制都包括以下占位符：</p>
<ul>
<li><code>username</code> mongodb用户名</li>
<li><code>password</code> mongodb密码</li>
<li><code>hostname</code> mongodb服务器ip地址</li>
<li><code>port</code> 端口</li>
<li><code>authenticationDb</code> 包含用户身份验证数据的mongodb数据库。如果省略此选项，驱动程序将使用默认值admin</li>
</ul>
<h5 id="默认方式"><a href="#默认方式" class="headerlink" title="默认方式"></a>默认方式</h5><p>默认机制使用以下身份验证机制之一，具体取决于服务器支持的mongodb版本</p>
<table>
<thead>
<tr>
<th>机制</th>
<th>版本</th>
</tr>
</thead>
<tbody><tr>
<td><code>SCRAM-SHA-256</code></td>
<td>Mongodb4.0及更高版本</td>
</tr>
<tr>
<td><code>SCRM-SHA-1</code></td>
<td>MongoDB3.0、3.2、3.4和3.6</td>
</tr>
<tr>
<td><code>MONGODB-CR</code></td>
<td>MongoDB及更早版本</td>
</tr>
</tbody></table>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">credential <span class="token operator">:=</span> options<span class="token punctuation">.</span>Credential<span class="token punctuation">&#123;</span>
   AuthSource<span class="token punctuation">:</span> <span class="token string">"&lt;authenticationDb>"</span><span class="token punctuation">,</span>
   Username<span class="token punctuation">:</span> <span class="token string">"&lt;username>"</span><span class="token punctuation">,</span>
   Password<span class="token punctuation">:</span> <span class="token string">"&lt;password>"</span><span class="token punctuation">,</span>
<span class="token punctuation">&#125;</span>
clientOpts <span class="token operator">:=</span> options<span class="token punctuation">.</span><span class="token function">Client</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">ApplyURI</span><span class="token punctuation">(</span><span class="token string">"mongodb://&lt;hostname>:&lt;port>"</span><span class="token punctuation">)</span><span class="token punctuation">.</span>
   <span class="token function">SetAuth</span><span class="token punctuation">(</span>credential<span class="token punctuation">)</span>

client<span class="token punctuation">,</span> err <span class="token operator">:=</span> mongo<span class="token punctuation">.</span><span class="token function">Connect</span><span class="token punctuation">(</span>context<span class="token punctuation">.</span><span class="token function">TODO</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> clientOpts<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<h5 id="SCRAM-SHA-256"><a href="#SCRAM-SHA-256" class="headerlink" title="SCRAM-SHA-256"></a>SCRAM-SHA-256</h5><blockquote>
<p><strong>SCRAM-SHA-256****是从 MongoDB 4.0 开始的 MongoDB 默认身份验证方法。</strong></p>
</blockquote>
<p><code>SCRAM-SHA-256</code>是一种加盐质询-响应身份验证机制 (SCRAM)，它使用您的用户名和密码（通过算法加密）<code>SHA-256</code> 来对您的用户进行身份验证。</p>
<p>要指定<code>SCRAM-SHA-256</code>身份验证机制，请为 <code>AuthMechanism</code>选项分配值<code>&quot;SCRAM-SHA-256&quot;</code>：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">credential <span class="token operator">:=</span> options<span class="token punctuation">.</span>Credential<span class="token punctuation">&#123;</span>
   AuthMechanism<span class="token punctuation">:</span> <span class="token string">"SCRAM-SHA-256"</span><span class="token punctuation">,</span>
   AuthSource<span class="token punctuation">:</span> <span class="token string">"&lt;authenticationDb>"</span><span class="token punctuation">,</span>
   Username<span class="token punctuation">:</span> <span class="token string">"&lt;username>"</span><span class="token punctuation">,</span>
   Password<span class="token punctuation">:</span> <span class="token string">"&lt;password>"</span><span class="token punctuation">,</span>
<span class="token punctuation">&#125;</span>
clientOpts <span class="token operator">:=</span> options<span class="token punctuation">.</span><span class="token function">Client</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">ApplyURI</span><span class="token punctuation">(</span><span class="token string">"mongodb://&lt;hostname>:&lt;port>"</span><span class="token punctuation">)</span><span class="token punctuation">.</span>
   <span class="token function">SetAuth</span><span class="token punctuation">(</span>credential<span class="token punctuation">)</span>

client<span class="token punctuation">,</span> err <span class="token operator">:=</span> mongo<span class="token punctuation">.</span><span class="token function">Connect</span><span class="token punctuation">(</span>context<span class="token punctuation">.</span><span class="token function">TODO</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> clientOpts<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h5 id="SCRAM-SHA-1"><a href="#SCRAM-SHA-1" class="headerlink" title="SCRAM-SHA-1"></a>SCRAM-SHA-1</h5><blockquote>
<p><strong>SCRAM-SHA-1****是 MongoDB 版本 3.0、3.2、3.4 和 3.6 的默认身份验证方法。</strong></p>
</blockquote>
<p><code>SCRAM-SHA-1</code>是一种加盐质询响应机制 (SCRAM)，它使用您的用户名和密码（通过算法加密）<code>SHA-1</code>来验证您的用户。</p>
<p>要指定<code>SCRAM-SHA-1</code>身份验证机制，请为 <code>AuthMechanism</code>选项分配值<code>&quot;SCRAM-SHA-1&quot;</code>：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">credential <span class="token operator">:=</span> options<span class="token punctuation">.</span>Credential<span class="token punctuation">&#123;</span>
   AuthMechanism<span class="token punctuation">:</span> <span class="token string">"SCRAM-SHA-1"</span><span class="token punctuation">,</span>
   AuthSource<span class="token punctuation">:</span> <span class="token string">"&lt;authenticationDb>"</span><span class="token punctuation">,</span>
   Username<span class="token punctuation">:</span> <span class="token string">"&lt;username>"</span><span class="token punctuation">,</span>
   Password<span class="token punctuation">:</span> <span class="token string">"&lt;password>"</span><span class="token punctuation">,</span>
<span class="token punctuation">&#125;</span>
clientOpts <span class="token operator">:=</span> options<span class="token punctuation">.</span><span class="token function">Client</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">ApplyURI</span><span class="token punctuation">(</span><span class="token string">"mongodb://&lt;hostname>:&lt;port>"</span><span class="token punctuation">)</span><span class="token punctuation">.</span>
   <span class="token function">SetAuth</span><span class="token punctuation">(</span>credential<span class="token punctuation">)</span>

client<span class="token punctuation">,</span> err <span class="token operator">:=</span> mongo<span class="token punctuation">.</span><span class="token function">Connect</span><span class="token punctuation">(</span>context<span class="token punctuation">.</span><span class="token function">TODO</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> clientOpts<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<h4 id="连接测试"><a href="#连接测试" class="headerlink" title="连接测试"></a>连接测试</h4><pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token punctuation">(</span>
    <span class="token string">"context"</span> <span class="token comment">// 用于在函数之间传递上下文信息，以支持控制连接和请求的声明周期</span>
    <span class="token string">"fmt"</span>
    <span class="token string">"go.mongodb.org/mongo-driver/bson"</span>           <span class="token comment">// 用于处理mongodb的bson数据</span>
    <span class="token string">"go.mongodb.org/mongo-driver/bson/primitive"</span> <span class="token comment">// 用于处理mongodb的objectid类型</span>
    <span class="token string">"go.mongodb.org/mongo-driver/mongo"</span>          <span class="token comment">// mongodb官方go驱动</span>
    <span class="token string">"go.mongodb.org/mongo-driver/mongo/options"</span>  <span class="token comment">// 用于设置mongodb连接选项</span>
    <span class="token string">"time"</span>
<span class="token punctuation">)</span>

<span class="token keyword">var</span> client <span class="token operator">*</span>mongo<span class="token punctuation">.</span>Client     <span class="token comment">// 定义客户端连接</span>
<span class="token keyword">var</span> database <span class="token operator">*</span>mongo<span class="token punctuation">.</span>Database <span class="token comment">// 数据库实例</span>
<span class="token keyword">var</span> users <span class="token operator">*</span>mongo<span class="token punctuation">.</span>Collection  <span class="token comment">// 集合实例</span>

<span class="token keyword">func</span> <span class="token function">init</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token comment">//const uri = "mongodb://dujie:123456@localhost:27017"</span>
    <span class="token comment">// mongodb连接字符串</span>
    <span class="token keyword">const</span> uri <span class="token operator">=</span> <span class="token string">"mongodb://localhost:27017"</span>
    <span class="token comment">// 创建凭据对象，用于身份验证</span>
    credential <span class="token operator">:=</span> options<span class="token punctuation">.</span>Credential<span class="token punctuation">&#123;</span>
        AuthSource<span class="token punctuation">:</span> <span class="token string">"test"</span><span class="token punctuation">,</span>
        Username<span class="token punctuation">:</span>   <span class="token string">"dujie"</span><span class="token punctuation">,</span>
        Password<span class="token punctuation">:</span>   <span class="token string">"123456"</span><span class="token punctuation">,</span>
    <span class="token punctuation">&#125;</span>
    <span class="token comment">//  options.Client().ApplyURI(uri) 创建一个连接选项，SetAuth(credential) 设置身份验证，  SetConnectTimeout设置连接超时时间</span>
    opts <span class="token operator">:=</span> options<span class="token punctuation">.</span><span class="token function">Client</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">ApplyURI</span><span class="token punctuation">(</span>uri<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">SetAuth</span><span class="token punctuation">(</span>credential<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">SetConnectTimeout</span><span class="token punctuation">(</span>time<span class="token punctuation">.</span>Second <span class="token operator">*</span> <span class="token number">3</span><span class="token punctuation">)</span>
    <span class="token comment">//opts := options.Client().ApplyURI(uri).SetConnectTimeout(time.Second * 3)</span>
    <span class="token keyword">var</span> err <span class="token builtin">error</span>
    <span class="token comment">// mongo.Connect 连接到mongodb数据库，返回客户端实例</span>
    client<span class="token punctuation">,</span> err <span class="token operator">=</span> mongo<span class="token punctuation">.</span><span class="token function">Connect</span><span class="token punctuation">(</span>context<span class="token punctuation">.</span><span class="token function">TODO</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> opts<span class="token punctuation">)</span>
    <span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
        fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"1 ~~~~"</span><span class="token punctuation">,</span> err<span class="token punctuation">)</span>
    <span class="token punctuation">&#125;</span>
    <span class="token comment">// 测试与数据库的连接是否正常</span>
    err <span class="token operator">=</span> client<span class="token punctuation">.</span><span class="token function">Ping</span><span class="token punctuation">(</span>context<span class="token punctuation">.</span><span class="token function">TODO</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token boolean">nil</span><span class="token punctuation">)</span>
    <span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
        fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"ping  ~~~~"</span><span class="token punctuation">,</span> err<span class="token punctuation">)</span>
    <span class="token punctuation">&#125;</span>
    <span class="token comment">// 获取数据库实例</span>
    database <span class="token operator">=</span> client<span class="token punctuation">.</span><span class="token function">Database</span><span class="token punctuation">(</span><span class="token string">"test"</span><span class="token punctuation">)</span>
    <span class="token comment">// 获取集合（表）实例</span>
    users <span class="token operator">=</span> database<span class="token punctuation">.</span><span class="token function">Collection</span><span class="token punctuation">(</span><span class="token string">"users"</span><span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>database<span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>users<span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>

<span class="token keyword">type</span> User <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
    <span class="token comment">// `bson:"_id,omitempty" 表示在BSON序列化和反序列化时将该字段映射到数据库中的_id字段，</span>
    Id    primitive<span class="token punctuation">.</span>ObjectID <span class="token string">`bson:"_id,omitempty"`</span>
    Name  <span class="token builtin">string</span>
    Age   <span class="token builtin">int</span>
    Score <span class="token builtin">float64</span>
<span class="token punctuation">&#125;</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">var</span> u User

    err <span class="token operator">:=</span> users<span class="token punctuation">.</span><span class="token function">FindOne</span><span class="token punctuation">(</span>context<span class="token punctuation">.</span><span class="token function">TODO</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> bson<span class="token punctuation">.</span>M<span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Decode</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>u<span class="token punctuation">)</span>
    <span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
        fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
    <span class="token punctuation">&#125;</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>u<span class="token punctuation">)</span>
    <span class="token keyword">defer</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        err <span class="token operator">:=</span> client<span class="token punctuation">.</span><span class="token function">Disconnect</span><span class="token punctuation">(</span>context<span class="token punctuation">.</span><span class="token function">TODO</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
        <span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
            fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"2 ~~~~"</span><span class="token punctuation">,</span> err<span class="token punctuation">)</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="基本概念"><a href="#基本概念" class="headerlink" title="基本概念"></a>基本概念</h3><p>MongoDB中可以创建使用多个库，但是有一些数据库名是保留的，可以直接访问这些有特殊作用的数据库。</p>
<ul>
<li><p>admin：从权限的角度来看，这是”root”数据库。要是将一个用户添加到这个数据库中，这个用户自动继承所有数据库的权限，一些特定的服务器端命令也只能从这个数据库运行，比如列出所有数据库或者关闭服务器。</p>
<ul>
<li><code>admin</code>数据库是MongoDB的管理数据库，只有具有管理员权限的用户才能访问它。</li>
<li>在<code>admin</code>数据库中，可以进行用户管理、权限设置、数据库备份和还原等操作。</li>
<li>通常，管理员会在<code>admin</code>数据库下创建其他数据库的用户，并为这些用户分配相应的权限。</li>
</ul>
</li>
<li><p>local：这个数据永远不会被复制，可以用来存储限于本地单台服务器的任意集合。</p>
<ul>
<li><code>local</code>数据库也是与分片相关的数据库，但它只在每个分片节点上存在。</li>
<li><code>local</code>数据库用于存储分片节点的复制集信息和本地操作日志。</li>
<li>当一个节点作为分片副本集的成员时，它会在<code>local</code>数据库中记录与副本集相关的信息。</li>
</ul>
</li>
<li><p>config：当Mongo用于分片设置时，config数据库在内部使用，用于保存分片的相关信息。</p>
<ul>
<li><code>config</code>数据库是用于支持MongoDB的分片（Sharding）功能的配置数据库。</li>
<li>当MongoDB部署为分片集群时，<code>config</code>数据库中会存储与分片有关的配置信息，如分片键、分片节点等。</li>
<li>分片配置服务器会维护<code>config</code>数据库中的信息，用于管理数据的分片和迁移。</li>
</ul>
</li>
</ul>
<table>
<thead>
<tr>
<th>RDBMS</th>
<th>MongoDB</th>
</tr>
</thead>
<tbody><tr>
<td>Database</td>
<td>Database</td>
</tr>
<tr>
<td>Table</td>
<td>Collection</td>
</tr>
<tr>
<td>Row</td>
<td>Document</td>
</tr>
<tr>
<td>Column</td>
<td>Field</td>
</tr>
<tr>
<td>Join</td>
<td>Embedded Document嵌入文档或Reference引入</td>
</tr>
<tr>
<td>Primary Key</td>
<td>主键（MongoDB提供了key为_id）</td>
</tr>
</tbody></table>
<p>Go Driver使用，官方博客：<a target="_blank" rel="noopener" href="https://www.mongodb.com/blog/post/mongodb-go-driver-tutorial">https://www.mongodb.com/blog/post/mongodb-go-driver-tutorial</a></p>
<h4 id="数据封装"><a href="#数据封装" class="headerlink" title="数据封装"></a>数据封装</h4><p>结构体定义<a target="_blank" rel="noopener" href="https://www.mongodb.com/docs/drivers/go/current/usage-examples/findOne/#find-a-document">https://www.mongodb.com/docs/drivers/go/current/usage-examples/findOne/#find-a-document</a></p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">type</span> Restaurant <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
	ID           primitive<span class="token punctuation">.</span>ObjectID <span class="token string">`bson:"_id"`</span>
	Name         <span class="token builtin">string</span>
	RestaurantId <span class="token builtin">string</span> <span class="token string">`bson:"restaurant_id"`</span>
	Cuisine      <span class="token builtin">string</span>
	Address      <span class="token keyword">interface</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
	Borough      <span class="token builtin">string</span>
	Grades       <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token keyword">interface</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">type</span> User <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
 ID   primitive<span class="token punctuation">.</span>ObjectID <span class="token string">`bson:"_id,omitempty"`</span>
 Name <span class="token builtin">string</span>
 Age  <span class="token builtin">int</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>u User<span class="token punctuation">)</span> <span class="token function">String</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">string</span> <span class="token punctuation">&#123;</span>
 <span class="token keyword">return</span> fmt<span class="token punctuation">.</span><span class="token function">Sprintf</span><span class="token punctuation">(</span><span class="token string">"&lt;%s: %s,%d>"</span><span class="token punctuation">,</span> u<span class="token punctuation">.</span>ID<span class="token punctuation">,</span> u<span class="token punctuation">.</span>Name<span class="token punctuation">,</span> u<span class="token punctuation">.</span>Age<span class="token punctuation">)</span> <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>结构体Tag 参考：<a target="_blank" rel="noopener" href="https://www.mongodb.com/docs/drivers/go/current/fundamentals/bson/#struct-tags"> https://www.mongodb.com/docs/drivers/go/current/fundamentals/bson/#struct-tags</a></p>
<table>
<thead>
<tr>
<th>结构体标签</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td><code>omitempty</code></td>
<td>如果将字段设置为与字段类型对应的零值，则不会对字段进行编辑，一般用于设置_id</td>
</tr>
<tr>
<td><code>minsize</code></td>
<td>如果字段类型为<code>int64</code> 、<code>uint32</code> 或<code>uint64</code> 类型，并且该字段的值可以放入有符号<code>int32</code> 中，则该字段将被序列化为<code>BSON int32</code> ，而不是<code>BSON int64</code> 。如果该值无法容纳有符号的<code>int32</code> 则忽略此标记</td>
</tr>
<tr>
<td><code>truncate</code></td>
<td>如果字段类型是非浮点数字类型，则解组到该字段的BSON双精度将在小数点处被截断。</td>
</tr>
<tr>
<td><code>inline</code></td>
<td>如果字段类型是结构体或映射字段，则该字段在编组时展平，并在解组时取消展平。</td>
</tr>
</tbody></table>
<p>User结构体中ID一定要使用omitempty，新增结构体时，如果ID不设置则为零值提交，数据库中_id字段就是一串0。如果设置忽略零值，ID为0提交时会被忽略，数据库则自动生成_id中的id。</p>
<p>ObjectId有12字节组成，参考<code>bson/primitive/objectid.go/NewObjectID()函数</code> </p>
<ul>
<li>4字节时间戳</li>
<li>5字节进程唯一值</li>
<li>3字节随机数，每次加1</li>
</ul>
<h5 id="插入数据"><a href="#插入数据" class="headerlink" title="插入数据"></a>插入数据</h5><p>操作参考：<a target="_blank" rel="noopener" href="https://www.mongodb.com/docs/drivers/go/current/usage-examples/">https://www.mongodb.com/docs/drivers/go/current/usage-examples/</a></p>
<p>####### 插入单条文档</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">type</span> Restaurant <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
	Name         <span class="token builtin">string</span>
	RestaurantId <span class="token builtin">string</span>        <span class="token string">`bson:"restaurant_id,omitempty"`</span>
	Cuisine      <span class="token builtin">string</span>        <span class="token string">`bson:"cuisine,omitempty"`</span>
	Address      <span class="token keyword">interface</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>   <span class="token string">`bson:"address,omitempty"`</span>
	Borough      <span class="token builtin">string</span>        <span class="token string">`bson:"borough,omitempty"`</span>
	Grades       <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token keyword">interface</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span> <span class="token string">`bson:"grades,omitempty"`</span>
<span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>当结构<code>omitempty</code> 标记留空时，它会缺省插入文档中的相应字段。</p>
<p>以下示例将新文档插入到<code>restaurants</code> 集合中</p>
<blockquote>
<p><strong>不存在的数据库和集合</strong></p>
</blockquote>
<blockquote>
<p>如果执行写入操作时所需的数据库和集合不存在，服务器会隐式创建它们</p>
</blockquote>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">coll <span class="token operator">:=</span> client<span class="token punctuation">.</span><span class="token function">Database</span><span class="token punctuation">(</span><span class="token string">"sample_restaurants"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Collection</span><span class="token punctuation">(</span><span class="token string">"restaurants"</span><span class="token punctuation">)</span>
newRestaurant <span class="token operator">:=</span> Restaurant<span class="token punctuation">&#123;</span>Name<span class="token punctuation">:</span> <span class="token string">"8282"</span><span class="token punctuation">,</span> Cuisine<span class="token punctuation">:</span> <span class="token string">"Korean"</span><span class="token punctuation">&#125;</span>

result<span class="token punctuation">,</span> err <span class="token operator">:=</span> coll<span class="token punctuation">.</span><span class="token function">InsertOne</span><span class="token punctuation">(</span>context<span class="token punctuation">.</span><span class="token function">TODO</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> newRestaurant<span class="token punctuation">)</span>
<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
	<span class="token function">panic</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>结果：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token punctuation">&#123;</span>
  <span class="token string">"_id"</span><span class="token punctuation">:</span> <span class="token function">ObjectId</span><span class="token punctuation">(</span><span class="token string">"..."</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
  <span class="token string">"name"</span><span class="token punctuation">:</span> <span class="token string">"8282"</span><span class="token punctuation">,</span>
  <span class="token string">"cuisine"</span><span class="token punctuation">:</span> <span class="token string">"Korean"</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>####### 插入多条<br>可以使用该<code>InsertMany()</code> 方法将多个文档插入到集合中。</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">type</span> Restaurant <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
	Name         <span class="token builtin">string</span>
	RestaurantId <span class="token builtin">string</span>        <span class="token string">`bson:"restaurant_id,omitempty"`</span>
	Cuisine      <span class="token builtin">string</span>        <span class="token string">`bson:"cuisine,omitempty"`</span>
	Address      <span class="token keyword">interface</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>   <span class="token string">`bson:"address,omitempty"`</span>
	Borough      <span class="token builtin">string</span>        <span class="token string">`bson:"borough,omitempty"`</span>
	Grades       <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token keyword">interface</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span> <span class="token string">`bson:"grades,omitempty"`</span>
<span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>当结构<code>omitempty</code> <a target="_blank" rel="noopener" href="https://www.mongodb.com/docs/drivers/go/current/fundamentals/bson/#std-label-golang-struct-tags">标记</a>留空时，它会省略插入文档中的相应字段。</p>
<p>以下示例将两个新文档插入到<code>restaurants</code> 集合中：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">coll <span class="token operator">:=</span> client<span class="token punctuation">.</span><span class="token function">Database</span><span class="token punctuation">(</span><span class="token string">"sample_restaurants"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Collection</span><span class="token punctuation">(</span><span class="token string">"restaurants"</span><span class="token punctuation">)</span>
newRestaurants <span class="token operator">:=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token keyword">interface</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">&#123;</span>
	Restaurant<span class="token punctuation">&#123;</span>Name<span class="token punctuation">:</span> <span class="token string">"Rule of Thirds"</span><span class="token punctuation">,</span> Cuisine<span class="token punctuation">:</span> <span class="token string">"Japanese"</span><span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
	Restaurant<span class="token punctuation">&#123;</span>Name<span class="token punctuation">:</span> <span class="token string">"Madame Vo"</span><span class="token punctuation">,</span> Cuisine<span class="token punctuation">:</span> <span class="token string">"Vietnamese"</span><span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
<span class="token punctuation">&#125;</span>

result<span class="token punctuation">,</span> err <span class="token operator">:=</span> coll<span class="token punctuation">.</span><span class="token function">InsertMany</span><span class="token punctuation">(</span>context<span class="token punctuation">.</span><span class="token function">TODO</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> newRestaurants<span class="token punctuation">)</span>
<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
	<span class="token function">panic</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h5 id="BSON"><a href="#BSON" class="headerlink" title="BSON"></a>BSON</h5><p><a target="_blank" rel="noopener" href="https://www.mongodb.com/docs/drivers/go/current/fundamentals/bson/">https://www.mongodb.com/docs/drivers/go/current/fundamentals/bson/</a></p>
<p>将Go类型转换为BSON的过程称为编组，而相反的过程称为解组</p>
<p>MongoDB的Go库提供的构建BSON的数据分为4种</p>
<p>MongoDB以二进制表示形式存储文档，称为BSON允许轻松灵活的数据处理。</p>
<ul>
<li>D : An ordered representation of a BSON document (slice)，表示有序的，切片且元素是二元的</li>
<li>M : An unordered representation of a BSON document (map)，表示无序的，map且元素是kv对</li>
<li>A : An ordered representation of a BSON array  BSON数组的有序表示</li>
<li>E : A single element inside a D type  D类型内的单个元素</li>
</ul>
<p>以下示例演示如何使用 <code>bson.D</code>类型构造查询过滤器来匹配<code>quantity</code>字段值大于 100 的文档</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">filter <span class="token operator">:=</span> bson<span class="token punctuation">.</span>D<span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span><span class="token string">"quantity"</span><span class="token punctuation">,</span> bson<span class="token punctuation">.</span>D<span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span><span class="token string">"$gt"</span><span class="token punctuation">,</span> <span class="token number">100</span><span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<h5 id="查询"><a href="#查询" class="headerlink" title="查询"></a>查询</h5><p>####### 单条查询<br><code>bson.D&#123;&#123;"name","tom"&#125;&#125;</code> </p>
<ul>
<li>bson.D 是切片，D后的{}表示切片字面量定义</li>
<li>{“name”,”tom”} 表示一个结构体实例字面量定义<ul>
<li>“name” 是结构体的Key属性，类型是string</li>
<li>“tom”是结构体的value属性，类型是any</li>
</ul>
</li>
</ul>
<p><code>bson.M&#123;&quot;name&quot;:&quot;tom&quot;&#125;</code></p>
<ul>
<li>bson.M是map，M后的{} 表示该map的字面量定义</li>
<li>map类型为map[string]interface{}</li>
</ul>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// 找一条</span>
<span class="token keyword">func</span> <span class="token function">findOne</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
 <span class="token comment">// 条件</span>
 <span class="token comment">// filter := bson.D&#123;&#123;"name", "tom"&#125;&#125; // slice</span>
 <span class="token comment">// filter := bson.D&#123;&#123;"name", bson.D&#123;&#123;"$eq", "tom"&#125;&#125;&#125;&#125;</span>
 filter <span class="token operator">:=</span> bson<span class="token punctuation">.</span>M<span class="token punctuation">&#123;</span><span class="token string">"name"</span><span class="token punctuation">:</span> <span class="token string">"tom"</span><span class="token punctuation">&#125;</span> <span class="token comment">// map</span>
 <span class="token comment">// filter := bson.M&#123;"name": bson.M&#123;"$ne": "jerry"&#125;&#125;</span>
 <span class="token comment">// filter := bson.D&#123;&#125; // 没有条件全部都符合</span>
 <span class="token keyword">var</span> u User
 err <span class="token operator">:=</span> users<span class="token punctuation">.</span><span class="token function">FindOne</span><span class="token punctuation">(</span>context<span class="token punctuation">.</span><span class="token function">TODO</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> filter<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Decode</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>u<span class="token punctuation">)</span>
 <span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
 <span class="token keyword">if</span> err <span class="token operator">==</span> mongo<span class="token punctuation">.</span>ErrNoDocuments <span class="token punctuation">&#123;</span>
 <span class="token comment">// 说明没有任何匹配文档</span>
 log<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"没有匹配的文档"</span><span class="token punctuation">)</span>
 <span class="token keyword">return</span>
 <span class="token punctuation">&#125;</span>
 log<span class="token punctuation">.</span><span class="token function">Fatal</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
 <span class="token punctuation">&#125;</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>u<span class="token punctuation">)</span> <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>####### 多条查询</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// 查多条，遍历结果</span>
<span class="token keyword">func</span> <span class="token function">findMany1</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
 filter <span class="token operator">:=</span> bson<span class="token punctuation">.</span>M<span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span> <span class="token comment">// 无条件，全部符合</span>
 cursor<span class="token punctuation">,</span> err <span class="token operator">:=</span> users<span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span>context<span class="token punctuation">.</span><span class="token function">TODO</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> filter<span class="token punctuation">)</span>
 <span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
 log<span class="token punctuation">.</span><span class="token function">Fatal</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
 <span class="token punctuation">&#125;</span>
    <span class="token keyword">defer</span> cursor<span class="token punctuation">.</span><span class="token function">Close</span><span class="token punctuation">(</span>context<span class="token punctuation">.</span><span class="token function">TODO</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token comment">// 关闭游标</span>
    
 <span class="token keyword">var</span> results <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token operator">*</span>User
 <span class="token keyword">for</span> cursor<span class="token punctuation">.</span><span class="token function">Next</span><span class="token punctuation">(</span>context<span class="token punctuation">.</span><span class="token function">TODO</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
 <span class="token keyword">var</span> u User
 err <span class="token operator">=</span> cursor<span class="token punctuation">.</span><span class="token function">Decode</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>u<span class="token punctuation">)</span>
 <span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
 log<span class="token punctuation">.</span><span class="token function">Fatal</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
 <span class="token punctuation">&#125;</span>
 results <span class="token operator">=</span> <span class="token function">append</span><span class="token punctuation">(</span>results<span class="token punctuation">,</span> <span class="token operator">&amp;</span>u<span class="token punctuation">)</span> <span class="token comment">// 装入容器</span>
 <span class="token punctuation">&#125;</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>results<span class="token punctuation">)</span> <span class="token punctuation">&#125;</span>
<span class="token comment">// 查多条，成批装入容器</span>
<span class="token keyword">func</span> <span class="token function">findMany2</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
 filter <span class="token operator">:=</span> bson<span class="token punctuation">.</span>D<span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span> <span class="token comment">// 无条件，全部符合</span>
 <span class="token keyword">var</span> results <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token operator">*</span>User
 cursor<span class="token punctuation">,</span> err <span class="token operator">:=</span> users<span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span>context<span class="token punctuation">.</span><span class="token function">TODO</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> filter<span class="token punctuation">)</span>
 <span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
 log<span class="token punctuation">.</span><span class="token function">Fatal</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
 <span class="token punctuation">&#125;</span>
 <span class="token keyword">defer</span> cursor<span class="token punctuation">.</span><span class="token function">Close</span><span class="token punctuation">(</span>context<span class="token punctuation">.</span><span class="token function">TODO</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token comment">// 关闭游标</span>
 err <span class="token operator">=</span> cursor<span class="token punctuation">.</span><span class="token function">All</span><span class="token punctuation">(</span>context<span class="token punctuation">.</span><span class="token function">TODO</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token operator">&amp;</span>results<span class="token punctuation">)</span>
 <span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
 log<span class="token punctuation">.</span><span class="token function">Fatal</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
 <span class="token punctuation">&#125;</span>
 <span class="token keyword">for</span> i<span class="token punctuation">,</span> r <span class="token operator">:=</span> <span class="token keyword">range</span> results <span class="token punctuation">&#123;</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>i<span class="token punctuation">,</span> r<span class="token punctuation">)</span>
 <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h5 id="查询条件"><a href="#查询条件" class="headerlink" title="查询条件"></a>查询条件</h5><p>改造上面的findMany2函数，可以使用下面表格中不同的filter</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">findByFilter</span><span class="token punctuation">(</span>filter <span class="token keyword">interface</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
 <span class="token keyword">var</span> results <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token operator">*</span>User
 cursor<span class="token punctuation">,</span> err <span class="token operator">:=</span> users<span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span>context<span class="token punctuation">.</span><span class="token function">TODO</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> filter<span class="token punctuation">)</span>
 <span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
 log<span class="token punctuation">.</span><span class="token function">Fatal</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
 <span class="token punctuation">&#125;</span>
    <span class="token keyword">defer</span> cursor<span class="token punctuation">.</span><span class="token function">Close</span><span class="token punctuation">(</span>context<span class="token punctuation">.</span><span class="token function">TODO</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token comment">// 关闭游标</span>
 err <span class="token operator">=</span> cursor<span class="token punctuation">.</span><span class="token function">All</span><span class="token punctuation">(</span>context<span class="token punctuation">.</span><span class="token function">TODO</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token operator">&amp;</span>results<span class="token punctuation">)</span>
 <span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
 log<span class="token punctuation">.</span><span class="token function">Fatal</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
 <span class="token punctuation">&#125;</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>results<span class="token punctuation">)</span> <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<table>
<thead>
<tr>
<th><strong>比较符号</strong></th>
<th><strong>含义</strong></th>
<th><strong>filter示例</strong></th>
</tr>
</thead>
<tbody><tr>
<td>$gt</td>
<td>大于</td>
<td><code>bson.M&#123;&quot;age&quot;:bson.M&#123;&quot;$gt&quot;:32&#125;&#125;</code></td>
</tr>
<tr>
<td>$lt</td>
<td>小于</td>
<td><code>bson.M&#123;&quot;age&quot;:bson.M&#123;&quot;$lt&quot;:32&#125;&#125;</code></td>
</tr>
<tr>
<td>$lte</td>
<td>小于等于</td>
<td><code>bson.M&#123;&quot;age&quot;:bson.M&#123;&quot;$lte&quot;:32&#125;&#125;</code></td>
</tr>
<tr>
<td>$gte</td>
<td>大于等于</td>
<td><code>bson.M&#123;&quot;age&quot;:bson.M&#123;&quot;$gte&quot;:32&#125;&#125;</code></td>
</tr>
<tr>
<td>$ne</td>
<td>不等于</td>
<td><code>bson.M&#123;&quot;age&quot;:bson.M&#123;&quot;$ne&quot;:32&#125;&#125;</code></td>
</tr>
<tr>
<td>$eq</td>
<td>等于，可以不用这个符号</td>
<td><code>bson.M&#123;&quot;age&quot;: bson.M&#123;&quot;$eq&quot;: 20&#125;&#125;</code><br><code>bson.M&#123;&quot;age&quot;: 20&#125;</code></td>
</tr>
<tr>
<td>$in</td>
<td>在范围内</td>
<td><code>bson.M&#123;&quot;age&quot;:bson.M&#123;&quot;$in&quot;:[]int&#123;1,3,4&#125;&#125;&#125;</code></td>
</tr>
<tr>
<td>$nin</td>
<td>不在范围内</td>
<td><code>bson.M&#123;&quot;age&quot;:bson.M&#123;&quot;$nin&quot;:[]int&#123;1,3,4&#125;&#125;&#125;</code></td>
</tr>
</tbody></table>
<p><a target="_blank" rel="noopener" href="https://www.mongodb.com/docs/manual/reference/operator/query/and/">https://www.mongodb.com/docs/manual/reference/operator/query/and/</a></p>
<table>
<thead>
<tr>
<th><strong>逻辑符号</strong></th>
<th><strong>含义</strong></th>
<th><strong>filter示例</strong></th>
</tr>
</thead>
<tbody><tr>
<td>$and</td>
<td>与</td>
<td><code>bson.M&#123;&quot;$and&quot;:[]bson.M&#123;&#123;"name":"tom"&#125;,&#123;"age":33&#125;&#125;&#125;</code> <br><code>bson.M&#123;&quot;$and&quot;:[]bson.M&#123;&#123;"name":"tom"&#125;,&#123;"age":bson.M&#123;"$gt":32&#125;&#125;&#125;&#125;</code></td>
</tr>
<tr>
<td>$or</td>
<td>或</td>
<td><code>bson.M&#123;&quot;$or&quot;: []bson.M&#123;&#123;"name": "tom"&#125;, &#123;"age": bson.M&#123;"$lt":20&#125;&#125;&#125;&#125;</code></td>
</tr>
<tr>
<td>$not</td>
<td>非</td>
<td><code>bson.M&#123;&quot;age&quot;: bson.M&#123;&quot;$not&quot;:bson.M&#123;&quot;$gte&quot;:20&#125;&#125;&#125;</code></td>
</tr>
</tbody></table>
<p><code>bson.M&#123;&quot;age&quot;: bson.M&#123;&quot;$gte&quot;:20&#125;&#125;</code> 取反为<code>bson.M&#123;&quot;age&quot;:bson.M&#123;&quot;$not&quot;:bson.M&#123;&quot;$gte&quot;:20&#125;&#125;&#125;</code> </p>
<table>
<thead>
<tr>
<th>元素</th>
<th>含义</th>
<th>示例</th>
</tr>
</thead>
<tbody><tr>
<td>$exists</td>
<td>文档中是否有这个字段</td>
<td><code>bson.M&#123;&quot;Name&quot;:bson.M&#123;&quot;$exists&quot;:true&#125;&#125;</code></td>
</tr>
<tr>
<td>$type</td>
<td>字段是否是指定的类型</td>
<td><code>bson.M&#123;&quot;age&quot;:bson.M&#123;&quot;$type&quot;:16&#125;&#125;</code></td>
</tr>
</tbody></table>
<p><code>bson.M&#123;&quot;name&quot;:bson.M&#123;&quot;$exists&quot;:true&#125;&#125;</code> 标识所有具有Name字段的文档，注意Name和name不一样</p>
<p>常用类型，参考：<a target="_blank" rel="noopener" href="https://www.mongodb.com/docs/manual/reference/operator/query/type/#op._S_type">https://www.mongodb.com/docs/manual/reference/operator/query/type/#op._S_type</a></p>
<ul>
<li>字符串类型编码为2，别名为string</li>
<li>整型编码为16，别名为int</li>
<li>长整型编码为18，别名为long</li>
</ul>
<p>改造函数findByFilter为findAll</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">findAll</span><span class="token punctuation">(</span>filter <span class="token keyword">interface</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">,</span> opt <span class="token operator">*</span>options<span class="token punctuation">.</span>FindOptions<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
 <span class="token keyword">var</span> results <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token operator">*</span>User
 cursor<span class="token punctuation">,</span> err <span class="token operator">:=</span> users<span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span>context<span class="token punctuation">.</span><span class="token function">TODO</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> filter<span class="token punctuation">,</span> opt<span class="token punctuation">)</span>
 <span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
 log<span class="token punctuation">.</span><span class="token function">Fatal</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
 <span class="token punctuation">&#125;</span>
    <span class="token keyword">defer</span> cursor<span class="token punctuation">.</span><span class="token function">Close</span><span class="token punctuation">(</span>context<span class="token punctuation">.</span><span class="token function">TODO</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token comment">// 关闭游标</span>
    
 err <span class="token operator">=</span> cursor<span class="token punctuation">.</span><span class="token function">All</span><span class="token punctuation">(</span>context<span class="token punctuation">.</span><span class="token function">TODO</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token operator">&amp;</span>results<span class="token punctuation">)</span>
 <span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
 log<span class="token punctuation">.</span><span class="token function">Fatal</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
 <span class="token punctuation">&#125;</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>results<span class="token punctuation">)</span> <span class="token punctuation">&#125;</span>
<span class="token function">findAll</span><span class="token punctuation">(</span>filter<span class="token punctuation">,</span> options<span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">SetLimit</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="投影"><a href="#投影" class="headerlink" title="投影"></a>投影</h3><pre class="line-numbers language-go" data-language="go"><code class="language-go">filter <span class="token operator">:=</span> bson<span class="token punctuation">.</span>M<span class="token punctuation">&#123;</span><span class="token string">"age"</span><span class="token punctuation">:</span> bson<span class="token punctuation">.</span>M<span class="token punctuation">&#123;</span><span class="token string">"$gt"</span><span class="token punctuation">:</span> <span class="token number">18</span><span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span>
opt <span class="token operator">:=</span> options<span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
opt<span class="token punctuation">.</span><span class="token function">SetProjection</span><span class="token punctuation">(</span>bson<span class="token punctuation">.</span>M<span class="token punctuation">&#123;</span><span class="token string">"name"</span><span class="token punctuation">:</span> <span class="token boolean">false</span><span class="token punctuation">,</span> <span class="token string">"age"</span><span class="token punctuation">:</span> <span class="token boolean">false</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span> <span class="token comment">// name、age字段不投影，都显示为零值</span>
<span class="token function">findAll</span><span class="token punctuation">(</span>filter<span class="token punctuation">,</span> opt<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">opt<span class="token punctuation">.</span><span class="token function">SetProjection</span><span class="token punctuation">(</span>bson<span class="token punctuation">.</span>M<span class="token punctuation">&#123;</span><span class="token string">"name"</span><span class="token punctuation">:</span> <span class="token boolean">true</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span> <span class="token comment">// name投影，age字段零值显示</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>


<h3 id="排序"><a href="#排序" class="headerlink" title="排序"></a>排序</h3><pre class="line-numbers language-go" data-language="go"><code class="language-go">opt<span class="token punctuation">.</span><span class="token function">SetSort</span><span class="token punctuation">(</span>bson<span class="token punctuation">.</span>M<span class="token punctuation">&#123;</span><span class="token string">"age"</span><span class="token punctuation">:</span> <span class="token number">1</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span> <span class="token comment">// 升序</span>
opt<span class="token punctuation">.</span><span class="token function">SetSort</span><span class="token punctuation">(</span>bson<span class="token punctuation">.</span>M<span class="token punctuation">&#123;</span><span class="token string">"age"</span><span class="token punctuation">:</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span> <span class="token comment">// 降序</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<h3 id="分页"><a href="#分页" class="headerlink" title="分页"></a>分页</h3><pre class="line-numbers language-go" data-language="go"><code class="language-go">opt<span class="token punctuation">.</span><span class="token function">SetSkip</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span>  <span class="token comment">// offset</span>
opt<span class="token punctuation">.</span><span class="token function">SetLimit</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span> <span class="token comment">// limit</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<h3 id="更新"><a href="#更新" class="headerlink" title="更新"></a>更新</h3><table>
<thead>
<tr>
<th>更新操作符</th>
<th>含义</th>
<th>示例</th>
</tr>
</thead>
<tbody><tr>
<td>$inc</td>
<td>对给定字段数字值增减</td>
<td><code>bson.M&#123;&quot;$inc&quot;:bson.M&#123;&quot;age&quot;: -5&#125;&#125;</code></td>
</tr>
<tr>
<td>$set</td>
<td>设置字段值，如果字段不存在则创建</td>
<td><code>bson.M&#123;&quot;$set&quot;:bson.M&#123;&quot;gender&quot;:&quot;M&quot;&#125;&#125;</code></td>
</tr>
<tr>
<td>$unset</td>
<td>移除字段</td>
<td><code>&#123;&#39;$unset&#39;:&#123;&#39;Name&#39;:&quot;&quot;&#125;&#125;</code></td>
</tr>
</tbody></table>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// 更新一个</span>
<span class="token keyword">func</span> <span class="token function">updateOne</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
 filter <span class="token operator">:=</span> bson<span class="token punctuation">.</span>M<span class="token punctuation">&#123;</span><span class="token string">"age"</span><span class="token punctuation">:</span> bson<span class="token punctuation">.</span>M<span class="token punctuation">&#123;</span><span class="token string">"$exists"</span><span class="token punctuation">:</span> <span class="token boolean">true</span><span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span> <span class="token comment">// 所有有age字段的文档</span>
 update <span class="token operator">:=</span> bson<span class="token punctuation">.</span>M<span class="token punctuation">&#123;</span><span class="token string">"$inc"</span><span class="token punctuation">:</span> bson<span class="token punctuation">.</span>M<span class="token punctuation">&#123;</span><span class="token string">"age"</span><span class="token punctuation">:</span> <span class="token operator">-</span><span class="token number">5</span><span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span>      <span class="token comment">// age字段减5</span>
 ur<span class="token punctuation">,</span> err <span class="token operator">:=</span> users<span class="token punctuation">.</span><span class="token function">UpdateOne</span><span class="token punctuation">(</span>context<span class="token punctuation">.</span><span class="token function">TODO</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> filter<span class="token punctuation">,</span> update<span class="token punctuation">)</span>
 <span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
 log<span class="token punctuation">.</span><span class="token function">Fatal</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
 <span class="token punctuation">&#125;</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>ur<span class="token punctuation">.</span>MatchedCount<span class="token punctuation">,</span> ur<span class="token punctuation">.</span>ModifiedCount<span class="token punctuation">)</span> <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// 更新多个</span>
<span class="token keyword">func</span> <span class="token function">updateMany</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
 filter <span class="token operator">:=</span> bson<span class="token punctuation">.</span>M<span class="token punctuation">&#123;</span><span class="token string">"age"</span><span class="token punctuation">:</span> bson<span class="token punctuation">.</span>M<span class="token punctuation">&#123;</span><span class="token string">"$exists"</span><span class="token punctuation">:</span> <span class="token boolean">true</span><span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span> <span class="token comment">// 所有有age字段的文档</span>
 update <span class="token operator">:=</span> bson<span class="token punctuation">.</span>M<span class="token punctuation">&#123;</span><span class="token string">"$set"</span><span class="token punctuation">:</span> bson<span class="token punctuation">.</span>M<span class="token punctuation">&#123;</span><span class="token string">"gender"</span><span class="token punctuation">:</span> <span class="token string">"M"</span><span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span>  <span class="token comment">// 为符合条件的文档设置gender字段</span>
 users<span class="token punctuation">.</span><span class="token function">UpdateMany</span><span class="token punctuation">(</span>context<span class="token punctuation">.</span><span class="token function">TODO</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> filter<span class="token punctuation">,</span> update<span class="token punctuation">)</span> <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">update <span class="token operator">:=</span> bson<span class="token punctuation">.</span>M<span class="token punctuation">&#123;</span><span class="token string">"$unset"</span><span class="token punctuation">:</span> bson<span class="token punctuation">.</span>M<span class="token punctuation">&#123;</span><span class="token string">"gender"</span><span class="token punctuation">:</span> <span class="token string">""</span><span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span> <span class="token comment">// 为符合条件的文档移除gender字 段</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>


<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// 找到一批更新第一个，ReplaceOne更新除ID以外所有字段</span>
filter <span class="token operator">:=</span> bson<span class="token punctuation">.</span>M<span class="token punctuation">&#123;</span><span class="token string">"age"</span><span class="token punctuation">:</span> bson<span class="token punctuation">.</span>M<span class="token punctuation">&#123;</span><span class="token string">"$exists"</span><span class="token punctuation">:</span> <span class="token boolean">true</span><span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span> <span class="token comment">// 所有有age字段的文档</span>
replacement <span class="token operator">:=</span> User<span class="token punctuation">&#123;</span>Name<span class="token punctuation">:</span> <span class="token string">"Sam"</span><span class="token punctuation">,</span> Age<span class="token punctuation">:</span> <span class="token number">48</span><span class="token punctuation">&#125;</span>
ur<span class="token punctuation">,</span> err <span class="token operator">:=</span> users<span class="token punctuation">.</span><span class="token function">ReplaceOne</span><span class="token punctuation">(</span>context<span class="token punctuation">.</span><span class="token function">TODO</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> filter<span class="token punctuation">,</span> replacement<span class="token punctuation">)</span>
<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
    log<span class="token punctuation">.</span><span class="token function">Fatal</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span> <span class="token punctuation">&#125;</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>ur<span class="token punctuation">.</span>MatchedCount<span class="token punctuation">,</span> ur<span class="token punctuation">.</span>ModifiedCount<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="删除"><a href="#删除" class="headerlink" title="删除"></a>删除</h3><pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// 删除一个</span>
<span class="token keyword">func</span> <span class="token function">deleteOne</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
 filter <span class="token operator">:=</span> bson<span class="token punctuation">.</span>M<span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span> <span class="token comment">// 没有条件，匹配所有文档</span>
 dr<span class="token punctuation">,</span> err <span class="token operator">:=</span> users<span class="token punctuation">.</span><span class="token function">DeleteOne</span><span class="token punctuation">(</span>context<span class="token punctuation">.</span><span class="token function">TODO</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> filter<span class="token punctuation">)</span>
 <span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
 log<span class="token punctuation">.</span><span class="token function">Fatal</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
 <span class="token punctuation">&#125;</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>dr<span class="token punctuation">.</span>DeletedCount<span class="token punctuation">)</span> <span class="token punctuation">&#125;</span>
<span class="token comment">// 删除多个</span>
<span class="token keyword">func</span> <span class="token function">deleteMany</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
 filter <span class="token operator">:=</span> bson<span class="token punctuation">.</span>M<span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span> <span class="token comment">// 没有条件，匹配所有文档</span>
 dr<span class="token punctuation">,</span> err <span class="token operator">:=</span> users<span class="token punctuation">.</span><span class="token function">DeleteMany</span><span class="token punctuation">(</span>context<span class="token punctuation">.</span><span class="token function">TODO</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> filter<span class="token punctuation">)</span>
 <span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
 log<span class="token punctuation">.</span><span class="token function">Fatal</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
 <span class="token punctuation">&#125;</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>dr<span class="token punctuation">.</span>DeletedCount<span class="token punctuation">)</span> <span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><code>users.DeleteMany(context.TODO(), bson.M&#123;&#125;)</code> 删除所有文档，危险！</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="http://dycloudnavite.love">J.</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://dycloudnavite.love/2023/05/09/Go%E6%93%8D%E4%BD%9CMongoDB/">http://dycloudnavite.love/2023/05/09/Go%E6%93%8D%E4%BD%9CMongoDB/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://dycloudnavite.love" target="_blank">J.のblog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/dujie5416/tags/%E4%BA%91%E5%8E%9F%E7%94%9F/">云原生</a><a class="post-meta__tags" href="/dujie5416/tags/golang/">golang</a></div><div class="post_share"><div class="addthis_inline_share_toolbox"></div><script src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-5d034d84b42927bf" async="async"></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/dujie5416/img/wechat.jpg" target="_blank"><img class="post-qr-code-img" src="/dujie5416/img/wechat.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/dujie5416/img/alipay.jpg" target="_blank"><img class="post-qr-code-img" src="/dujie5416/img/alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/dujie5416/2023/05/10/%E8%BF%9B%E7%A8%8B%E7%BA%BF%E7%A8%8B/"><img class="prev-cover" src="/dujie5416/img/golang.png" onerror="onerror=null;src='/dujie5416/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">进程和线程</div></div></a></div><div class="next-post pull-right"><a href="/dujie5416/2023/05/06/Golang%E4%B8%AD%E7%9A%84GORM/"><img class="next-cover" src="/dujie5416/img/golang.png" onerror="onerror=null;src='/dujie5416/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Golang GORM使用</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/dujie5416/2023/05/20/Channel%E9%80%9A%E9%81%93/" title="Channel通道"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-05-20</div><div class="title">Channel通道</div></div></a></div><div><a href="/dujie5416/2023/05/06/Golang%E4%B8%AD%E7%9A%84GORM/" title="Golang GORM使用"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-05-06</div><div class="title">Golang GORM使用</div></div></a></div><div><a href="/dujie5416/2023/06/23/Gin%E6%A1%86%E6%9E%B6/" title="Gin框架"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-06-23</div><div class="title">Gin框架</div></div></a></div><div><a href="/dujie5416/2023/05/15/Golang%E5%8D%8F%E7%A8%8B/" title="Golang协程"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-05-15</div><div class="title">Golang协程</div></div></a></div><div><a href="/dujie5416/2023/04/17/Golang%E5%8F%98%E9%87%8F%E9%80%83%E9%80%B8%E2%80%94%E2%80%94%E5%A0%86%E3%80%81%E6%A0%88/" title="Golang变量逃逸————堆、栈"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-04-17</div><div class="title">Golang变量逃逸————堆、栈</div></div></a></div><div><a href="/dujie5416/2023/02/13/Golang%E5%AD%97%E7%AC%A6%E4%B8%B2string/" title="Golang字符串"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-02-13</div><div class="title">Golang字符串</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="lv-container" data-id="city" data-uid="MTAyMC81Njk5OS8zMzQ2Mw=="></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/dujie5416/img/touxiang.png" onerror="this.onerror=null;this.src='/dujie5416/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">J.</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/dujie5416/archives/"><div class="headline">文章</div><div class="length-num">73</div></a><a href="/dujie5416/tags/"><div class="headline">标签</div><div class="length-num">17</div></a><a href="/dujie5416/categories/"><div class="headline">分类</div><div class="length-num">11</div></a></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#MongoDB"><span class="toc-number">1.</span> <span class="toc-text">MongoDB</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AE%89%E8%A3%85"><span class="toc-number">1.0.0.1.</span> <span class="toc-text">安装</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%BF%90%E8%A1%8C"><span class="toc-number">1.0.1.</span> <span class="toc-text">运行</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6"><span class="toc-number">1.0.2.</span> <span class="toc-text">配置文件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AE%A2%E6%88%B7%E7%AB%AF"><span class="toc-number">1.0.3.</span> <span class="toc-text">客户端</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%AE%A2%E6%88%B7%E7%AB%AF%E8%BF%9E%E6%8E%A5"><span class="toc-number">1.0.3.0.1.</span> <span class="toc-text">客户端连接</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E9%A9%B1%E5%8A%A8"><span class="toc-number">1.0.3.0.2.</span> <span class="toc-text">驱动</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E8%BF%9E%E6%8E%A5%E5%AD%97%E7%AC%A6%E4%B8%B2"><span class="toc-number">1.0.3.0.3.</span> <span class="toc-text">连接字符串</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E8%B4%A6%E5%8F%B7%E5%AF%86%E7%A0%81%E8%AE%A4%E8%AF%81%E8%BF%9E%E6%8E%A5"><span class="toc-number">1.0.3.0.4.</span> <span class="toc-text">账号密码认证连接</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#%E6%94%AF%E6%8C%81%E7%9A%84%E6%9C%BA%E5%88%B6"><span class="toc-number">1.0.3.0.4.1.</span> <span class="toc-text">支持的机制</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#%E7%BA%A6%E5%AE%9A%E7%A4%BA%E4%BE%8B"><span class="toc-number">1.0.3.0.4.2.</span> <span class="toc-text">约定示例</span></a></li></ol></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E9%BB%98%E8%AE%A4%E6%96%B9%E5%BC%8F"><span class="toc-number">1.0.3.0.5.</span> <span class="toc-text">默认方式</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#SCRAM-SHA-256"><span class="toc-number">1.0.3.0.6.</span> <span class="toc-text">SCRAM-SHA-256</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#SCRAM-SHA-1"><span class="toc-number">1.0.3.0.7.</span> <span class="toc-text">SCRAM-SHA-1</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%BF%9E%E6%8E%A5%E6%B5%8B%E8%AF%95"><span class="toc-number">1.0.3.1.</span> <span class="toc-text">连接测试</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9F%BA%E6%9C%AC%E6%A6%82%E5%BF%B5"><span class="toc-number">1.0.4.</span> <span class="toc-text">基本概念</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%95%B0%E6%8D%AE%E5%B0%81%E8%A3%85"><span class="toc-number">1.0.4.1.</span> <span class="toc-text">数据封装</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%8F%92%E5%85%A5%E6%95%B0%E6%8D%AE"><span class="toc-number">1.0.4.1.1.</span> <span class="toc-text">插入数据</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#BSON"><span class="toc-number">1.0.4.1.2.</span> <span class="toc-text">BSON</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%9F%A5%E8%AF%A2"><span class="toc-number">1.0.4.1.3.</span> <span class="toc-text">查询</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%9F%A5%E8%AF%A2%E6%9D%A1%E4%BB%B6"><span class="toc-number">1.0.4.1.4.</span> <span class="toc-text">查询条件</span></a></li></ol></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%8A%95%E5%BD%B1"><span class="toc-number">1.0.5.</span> <span class="toc-text">投影</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%8E%92%E5%BA%8F"><span class="toc-number">1.0.6.</span> <span class="toc-text">排序</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%86%E9%A1%B5"><span class="toc-number">1.0.7.</span> <span class="toc-text">分页</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%9B%B4%E6%96%B0"><span class="toc-number">1.0.8.</span> <span class="toc-text">更新</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%A0%E9%99%A4"><span class="toc-number">1.0.9.</span> <span class="toc-text">删除</span></a></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/07/29/%E6%A0%B9%E6%8D%AErouter%E6%98%BE%E7%A4%BA%E5%B7%A6%E4%BE%A7%E8%8F%9C%E5%8D%95%E6%A0%8F%E9%9A%90%E8%97%8F%E6%9F%90%E4%B8%AA%E8%8F%9C%E5%8D%95%E9%80%89%E9%A1%B9/" title="vue3左侧菜单隐藏某选项"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="vue3左侧菜单隐藏某选项"/></a><div class="content"><a class="title" href="/dujie5416/2023/07/29/%E6%A0%B9%E6%8D%AErouter%E6%98%BE%E7%A4%BA%E5%B7%A6%E4%BE%A7%E8%8F%9C%E5%8D%95%E6%A0%8F%E9%9A%90%E8%97%8F%E6%9F%90%E4%B8%AA%E8%8F%9C%E5%8D%95%E9%80%89%E9%A1%B9/" title="vue3左侧菜单隐藏某选项">vue3左侧菜单隐藏某选项</a><time datetime="2023-07-29T06:32:00.000Z" title="发表于 2023-07-29 14:32:00">2023-07-29</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/07/13/Vue%E7%8A%B6%E6%80%81%E7%AE%A1%E7%90%86/" title="Vue状态管理"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="Vue状态管理"/></a><div class="content"><a class="title" href="/dujie5416/2023/07/13/Vue%E7%8A%B6%E6%80%81%E7%AE%A1%E7%90%86/" title="Vue状态管理">Vue状态管理</a><time datetime="2023-07-13T09:29:00.000Z" title="发表于 2023-07-13 17:29:00">2023-07-13</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/06/27/%E5%9F%BA%E4%BA%8EIOC%E8%A7%A3%E5%86%B3%E5%AF%B9%E8%B1%A1%E4%BE%9D%E8%B5%96%E9%97%AE%E9%A2%98/" title="基于IOC解决对象依赖问题"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="基于IOC解决对象依赖问题"/></a><div class="content"><a class="title" href="/dujie5416/2023/06/27/%E5%9F%BA%E4%BA%8EIOC%E8%A7%A3%E5%86%B3%E5%AF%B9%E8%B1%A1%E4%BE%9D%E8%B5%96%E9%97%AE%E9%A2%98/" title="基于IOC解决对象依赖问题">基于IOC解决对象依赖问题</a><time datetime="2023-06-27T03:32:00.000Z" title="发表于 2023-06-27 11:32:00">2023-06-27</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/06/23/Gin%E6%A1%86%E6%9E%B6/" title="Gin框架"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="Gin框架"/></a><div class="content"><a class="title" href="/dujie5416/2023/06/23/Gin%E6%A1%86%E6%9E%B6/" title="Gin框架">Gin框架</a><time datetime="2023-06-23T06:32:00.000Z" title="发表于 2023-06-23 14:32:00">2023-06-23</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/06/04/ServeMux%E3%80%81httprouter/" title="ServeMux、httprouter"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="ServeMux、httprouter"/></a><div class="content"><a class="title" href="/dujie5416/2023/06/04/ServeMux%E3%80%81httprouter/" title="ServeMux、httprouter">ServeMux、httprouter</a><time datetime="2023-06-04T03:32:00.000Z" title="发表于 2023-06-04 11:32:00">2023-06-04</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('/dujie5416/img/longzhu.png')"><div id="footer-wrap"><div class="copyright">&copy;2019 - 2024  <i id="heartbeat" class="fa fas fa-heartbeat"></i> J.</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a><a href="http://beian.miit.gov.cn/"  style="color:#f72b07" target="_blank">京ICP备2022023567号</a></div></div><link rel="stylesheet" href="https://fastly.jsdelivr.net/gh/HCLonely/images@master/others/heartbeat.min.css"></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="algolia-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="search-wrap"><div id="algolia-search-input"></div><hr/><div id="algolia-search-results"><div id="algolia-hits"></div><div id="algolia-pagination"></div><div id="algolia-info"><div class="algolia-stats"></div><div class="algolia-poweredBy"></div></div></div></div></div><div id="search-mask"></div></div><div id="rightMenu"><div class="rightMenu-group rightMenu-small"><div class="rightMenu-item" id="menu-backward"><i class="fa-solid fa-arrow-left"></i></div><div class="rightMenu-item" id="menu-forward"><i class="fa-solid fa-arrow-right"></i></div><div class="rightMenu-item" id="menu-refresh"><i class="fa-solid fa-arrow-rotate-right"></i></div><div class="rightMenu-item" id="menu-home"><i class="fa-solid fa-house"></i></div></div><div class="rightMenu-group rightMenu-line rightMenuOther"><a class="rightMenu-item menu-link" href="/archives/"><i class="fa-solid fa-archive"></i><span>文章归档</span></a><a class="rightMenu-item menu-link" href="/categories/"><i class="fa-solid fa-folder-open"></i><span>文章分类</span></a><a class="rightMenu-item menu-link" href="/tags/"><i class="fa-solid fa-tags"></i><span>文章标签</span></a></div><div class="rightMenu-group rightMenu-line rightMenuNormal"><a class="rightMenu-item menu-link" id="menu-radompage" href="/random/index.html"><i class="fa-solid fa-shoe-prints"></i><span>随便逛逛</span></a><div class="rightMenu-item" id="menu-translate"><i class="fa-solid fa-earth-asia"></i><span>繁简切换</span></div><div class="rightMenu-item" id="menu-darkmode"><i class="fa-solid fa-moon"></i><span>切换模式</span></div></div></div><div id="rightmenu-mask"></div><div><script src="/dujie5416/js/utils.js"></script><script src="/dujie5416/js/main.js"></script><script src="/dujie5416/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/algoliasearch/dist/algoliasearch-lite.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instantsearch.js/dist/instantsearch.production.min.js"></script><script src="/dujie5416/js/search/algolia.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><script>function loadLivere () {
  if (typeof LivereTower === 'object') {
    window.LivereTower.init()
  }
  else {
    (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
    })(document, 'script');
  }
}

if ('Livere' === 'Livere' || !false) {
  if (false) btf.loadComment(document.getElementById('lv-container'), loadLivere)
  else loadLivere()
}
else {
  function loadOtherComment () {
    loadLivere()
  }
}</script></div><script defer src="https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js"></script><script data-pjax defer src="https://npm.elemecdn.com/tzy-blog/lib/js/theme/chocolate.js"></script><canvas id="universe"></canvas><script defer src="/js/universe.js"></script><script defer data-pjax src="/js/rightMenu.js"></script><div class="aplayer no-destroy" data-id="7427714271" data-server="netease" data-type="playlist" data-fixed="true" data-mini="true" data-listFolded="false" data-order="random" data-lrctype="1" data-preload="none" data-autoplay="true" muted></div><script id="click-show-text" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/click-show-text.min.js" data-mobile="false" data-text="I,LOVE,YOU" data-fontsize="15px" data-random="false" async="async"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/metingjs/dist/Meting.min.js"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = ["meta[property=\"og:image\"]","meta[property=\"og:title\"]","meta[property=\"og:url\"]","head > title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show",".js-pjax"]

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.tocScrollFn && window.removeEventListener('scroll', window.tocScrollFn)
  window.scrollCollect && window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  document.getElementById('rightside').style.cssText = "opacity: ''; transform: ''"
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

  typeof disqusjs === 'object' && disqusjs.destroy()
})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><!-- hexo injector body_end start --><script data-pjax>
  function butterfly_clock_anzhiyu_injector_config(){
    var parent_div_git = document.getElementsByClassName('sticky_layout')[0];
    var item_html = '<div class="card-widget card-clock"><div class="card-glass"><div class="card-background"><div class="card-content"><div id="hexo_electric_clock"><img class="entered loading" id="card-clock-loading" src="https://cdn.cbd.int/hexo-butterfly-clock-anzhiyu/lib/loading.gif" style="height: 120px; width: 100%;" data-ll-status="loading"/></div></div></div></div></div>';
    console.log('已挂载butterfly_clock_anzhiyu')
    if(parent_div_git) {
      parent_div_git.insertAdjacentHTML("afterbegin",item_html)
    }
  }
  var elist = 'null'.split(',');
  var cpage = location.pathname;
  var epage = 'all';
  var qweather_key = '56289903f0d448dfbe8262dba0175f70';
  var gaud_map_key = '01603f2b2d08d0e947bb101e9d9b148b';
  var baidu_ak_key = 'undefined';
  var flag = 0;
  var clock_rectangle = '112.982279,28.19409';
  var clock_default_rectangle_enable = 'false';

  for (var i=0;i<elist.length;i++){
    if (cpage.includes(elist[i])){
      flag++;
    }
  }

  if ((epage ==='all')&&(flag == 0)){
    butterfly_clock_anzhiyu_injector_config();
  }
  else if (epage === cpage){
    butterfly_clock_anzhiyu_injector_config();
  }
  </script><script src="https://widget.qweather.net/simple/static/js/he-simple-common.js?v=2.0"></script><script data-pjax src="https://cdn.cbd.int/hexo-butterfly-clock-anzhiyu/lib/clock.min.js"></script><!-- hexo injector body_end end --><script src="/dujie5416/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"tagMode":false,"debug":false,"model":{"jsonPath":"/dujie5416/live2dw/assets/tororo.model.json"},"display":{"position":"right","width":150,"height":350,"hOffset":20,"vOffset":-20},"mobile":{"show":false},"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/"});</script><script async>window.onload=function(){var a=document.createElement('script'),b=document.getElementsByTagName('script')[0];a.type='text/javascript',a.async=!0,a.src='/sw-register.js?v='+Date.now(),b.parentNode.insertBefore(a,b)};</script></body></html>